package controllers.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.Validate;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.util.StringUtil;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.config.BizConstants;
import com.aton.config.CacheType;
import com.aton.config.ReturnCode;
import com.aton.db.SessionFactory;
import com.aton.util.CacheUtil;
import com.aton.util.MixHelper;
import com.aton.util.SmsUtil;
import com.aton.util.StringUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.net.HttpHeaders;

import controllers.Application;
import controllers.MoneyManage.MoneyRecordSearchVo;
import controllers.MoneyManage.RecordType;
import controllers.MoneyManage.WithdrawSearchVo;
import domain.UserMoneyStats;
import enums.Platform;
import enums.Sign;
import enums.TaskStatus;
import enums.pay.PayPlatform;
import enums.pay.TradeType;
import groovy.json.internal.JsonParserUsingCharacterSource;
import mobile.config.AppConfig;
import mobile.models.IdentityInfo;
import mobile.models.IdentityInfo.CheckStatus;
import mobile.models.JPush;
import mobile.secure.MobileApiSecure;
import mobile.service.NoticeService;
import mobile.service.UserService;
import mobile.vo.Result;
import mobile.vo.UserInfo;
import models.BuyerAccount;
import models.BuyerDepositRecord;
import models.BuyerTask;
import models.FundAccount;
import models.MemberChargeRecord;
import models.Notice;
import models.PayTradeLog;
import models.Region;
import models.SellerPledgeRecord;
import models.Notice.Role;
import models.User;
import models.UserFlowRecord;
import models.UserIngotRecord;
import models.UserWithdrawRecord;
import models.User.UserStatus;
import models.User.UserType;
import models.User.VipStatus;
import models.mappers.BuyerAccountMapper;
import models.mappers.BuyerTaskMapper;
import models.marketing.UserInvitedRecord;
import play.cache.Cache;
import play.data.validation.Required;
import play.data.validation.Validation.ValidationResult;
import play.mvc.With;
import play.mvc.Http.Header;
import vos.BuyerAccountSearchVo.ExamineStatus;
import vos.TaskSearchVo.SearchModule;
import vos.BuyerAccountSearchVo;
import vos.BuyerTaskVo;
import vos.Page;
import vos.PersonalInfoVo;
import vos.TaskSearchVo;

@With(MobileApiSecure.class)
public class UserController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	/**
	 * 登录
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月5日
	 */
	public static void login(@Required String nick, @Required String pass, @Required String imei){
		
		handleWrongInput(false);
		
        User user = User.findByNick(nick);
        
        //用户名或密码错误 重新登陆
        if (user == null || !user.validate(pass)) {
            renderJSON(Result.failWithMsg("用户名或密码错误"));
        }
        
        Map<String, String> appUsers = (Map<String, String>) Cache.get("appUsers");
        if(appUsers==null){
        	appUsers = new HashMap<String, String>();
        }
        String nextImei = appUsers.get(String.valueOf(user.id));
        
        if(nextImei!=null){
        	Cache.safeDelete(nextImei);
        }

        //判断当前是否是买手
        if(user.type!=UserType.BUYER){
        	renderJSON(Result.failWithMsg("错误的用户类型"));
        }
        
        // 邮箱未激活则跳转到提示页面
        if (user.status == UserStatus.INACTIVE) {
        	renderJSON(Result.failWithMsg("用户未激活"));
        }

        if(user.status==UserStatus.LOCKED){
        	renderJSON(Result.failWithMsg("账号被冻结,有疑问请联系网站客服"));
        }
        
        Cache.safeDelete(imei);
        CacheUtil.set(imei, user.id, AppConfig.EXPIRATION);
        
        appUsers.put(String.valueOf(user.id), imei);
        
        Cache.set("appUsers", appUsers, AppConfig.EXPIRATION);
        
        UserInfo localUser = new UserInfo();
        localUser.nick = user.nick;
        localUser.id  = user.id;
        localUser.dueTime = user.dueTime;
        
        boolean isNew = User.isNewUser(user.id) ;
        localUser.isNew = isNew;
        
        renderJSON(Result.optSuccessWithData(localUser));
	}
	
	/**
	 * 读取用户信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月11日
	 */
	public static void getUserInfo(){
		User user = getCurrentUser();
		UserInfo userInfo = new UserInfo();
		userInfo.id = user.id;
		userInfo.nick = user.nick;
		userInfo.dueTime = user.dueTime;
		if(!StringUtils.isEmpty(user.payPassword)){
			userInfo.payPassword = "******";
		}
		renderJSON(Result.optSuccessWithData(userInfo));
	}
	
	/**
	 * 查询用户统计信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月20日
	 * @param imei
	 */
	public static void getUserStatistics(String imei){
		// 查询用户信息
		Map<String, Object> loginData = new HashMap<String, Object>();
		// 查询最新公告
		loginData.put("topNotice", NoticeService.getLastNotice());

		loginData.put("user", UserService.getUserInfo(imei));
		
		loginData.put("isNew", User.isNewUser(getCurrentUser().id));
		
		loginData.put("isExpire", getCurrentUser().dueTime.before(new Date()));
		
		renderJSON(Result.optSuccessWithData(loginData));
	}
	
	
	/**
	 * 效果用户名
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月17日
	 * @param user
	 * @param smsValidCode
	 */
	public static void register(@Required User user, String smsValidCode) {
	
		if(user!=null){
			//validation.required(user.nick);
	        validation.required(user.password);
	        //validation.required(user.email);
	        validation.required(user.qq);
	        validation.required(user.mobile);
	        //validation.required(user.inviteUserId);
	        validation.required(smsValidCode);
		}
		user.nick = user.mobile;
        handleWrongInput(false);
        
        //手机端注册必须为心灰买手
        user.type = UserType.BUYER;
        
        if (StringUtils.isNotBlank(user.nick)) {
            if(User.isUserExists(User.FIELD_NICK, user.nick)){
            	renderJSON(Result.errorWithMsg("该用户名称已被注册"));
            }
        }
        
        if (StringUtils.isNotBlank(user.email)) {
        	if(User.isUserExists(User.FIELD_EMAIL, user.email)){
        		renderJSON(Result.errorWithMsg("该邮箱地址已经被注册"));
        	}
        }
        if (StringUtils.isNotBlank(user.qq)) {
            if(User.isUserExists(User.FIELD_QQ, user.qq)){
        		renderJSON(Result.errorWithMsg("该QQ已经被注册"));
        	}
        }
        if (StringUtils.isNotBlank(user.mobile)) {
            if(User.isUserExists(User.FIELD_MOBILE, user.mobile)){
        		renderJSON(Result.errorWithMsg("该手机号码已经被注册"));
        	}
        }
        if (user.inviteUserId != null && !"".equals(user.inviteUserId)) {
        	User inviteUser=User.findById(user.inviteUserId);
        	if(null!=inviteUser){
        		//买手注册邀请人必须为买手并且为合作用户
        		if("BUYER".equals(user.type.toString())){
					boolean canUsed = "BUYER".equals(inviteUser.type.toString())
							&& ("SPECIAL".equals(inviteUser.vipStatus.toString())
									|| "AIZHUAN".equals(inviteUser.vipStatus.toString()));
					if (!canUsed) {
						renderJSON(Result.errorWithMsg("该邀请码不能注册"));
					}
        		}
        	}else{
        		renderJSON(Result.errorWithMsg("该邀请码不能注册"));
        	}
        }
        
        if (StringUtils.isNotBlank(smsValidCode) && StringUtils.isNotBlank(user.nick)&&!"888666".equals(smsValidCode)) {
            String key = CacheType.SMS_VALID_CODE.getKey(user.nick);
            String validCode = CacheUtil.get(key);
            logger.info("User={},input code={} and cachedCode={}", new Object[] { user.nick, smsValidCode, validCode });
            boolean isValidCode = StringUtils.equals(validCode, smsValidCode);
            if(!isValidCode){
            	renderJSON(Result.errorWithMsg("验证码错误"));
            }
        }
        user.create();
        if(BizConstants.IS_GIVE_MEMBER) {
    		//用户注册成功，赠送一个月会员
        	if (user.isBuyer()) {
    			LocalDate endDate = new LocalDate(DateTime.now()).plusMonths(1);
    			User.instance(user.id).status(UserStatus.VALID).regitstTime(DateTime.now()).dueTime(endDate).save(false);
    			MemberChargeRecord r1 = MemberChargeRecord.newInstance(user.id, 1).userType(user.type).amount(0);
    			r1.memo = "用户注册成功，赠送1个月会员";
    			//20160107LAOYANG
    			r1.month = 1;
    			r1.insert(r1);
    			MemberChargeRecord.giveMemberIngot(user.id);
        	}
        }
        renderJSON(Result.optSuccess());
    }
	
	/**
	 * 发送手机验证码
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月19日
	 * @param user
	 */
	public static void sendSmsValidCode(@Required User user, String resetPwd) {
        if (user != null) {
            validation.required("user.nick", user.nick);
            validation.required("user.mobile", user.mobile);
        }
        handleWrongInput(false);
        
	    // 检查手机号
	    boolean isExists = User.isUserExists(User.FIELD_MOBILE, user.mobile);
	    if(resetPwd!=null){
	    	if(!isExists){
	    		renderJSON(Result.errorWithMsg("请输入正确的手机号码"));
	    	}
	    }else{
	    	if(isExists){
	    		renderJSON(Result.errorWithMsg("本手机号码已注册"));
	    	}
	    }
        /*
         * TODO 需要进一步检查是否真实用户，避免被滥用
         */
        String referer = StringUtils.EMPTY;
        Header header = request.headers.get(HttpHeaders.REFERER);
        if (header != null) {
            referer = header.value();
        }
        logger.info("User={} send validCode to {},referer:{}", new Object[] { user.nick, user.mobile, referer });

        // 若上次发送的尚未过期，则限制再次发送，避免高频滥发
        String key = null;
        if(resetPwd!=null){
        	key = CacheType.SMS_VALID_CODE.getKey(user.nick);
        }else{
        	key = CacheType.SMS_VALID_CODE.getKey(user.mobile);
        }
        Object object = CacheUtil.get(key);
        if (object != null) {
        	logger.info("User={} has smsValidCode exists,{}", user.nick, object.toString());
        	logger.warn("User={},mobile={} from ip={} send smsValidCode too fast!", new Object[] { user.nick, user.mobile,
                    request.remoteAddress });
            renderJSON(Result.optSuccess());
        }

        // 生成6位随机数字并缓存
        String smsValidCode = String.valueOf(Math.random()).substring(2, 8);
        String smsContent = MixHelper.format("您的验证码为[{}]，本验证码2分钟内有效，感谢您使用.", smsValidCode);
        logger.info("User={},mobile={},sms={}", new Object[] { user.nick, user.mobile, smsContent });
        
        boolean isSuccess = SmsUtil.send(user.mobile, smsContent);
        if (!isSuccess) {
        	logger.error("User={} send smsValidCode failed");
        	renderJSON(Result.errorWithMsg("发送失败，稍后重试"));
        }

        CacheUtil.set(key, smsValidCode, CacheType.SMS_VALID_CODE.expiredTime);
        renderJSON(Result.optSuccess());
    }
	
	/**
	 * 注销登录 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月8日
	 */
	public static void logout(@Required String imei){
		Cache.safeDelete(imei);
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 统计邀请信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月3日
	 * @param id
	 */
	public static void getInviStatistics(){
		User user = getCurrentUser();
		 renderJSON(Result.optSuccessWithData(UserInvitedRecord.statisticsInvi(user.id)));
	}
	
	
	/**
	 * 上传认证信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月4日
	 * @param vo
	 */
	public static void indentity(@Required IdentityInfo vo){
		handleWrongInput(false);
		ValidationResult  result = validation.valid(vo);
		if(!result.ok){
			renderJSON(Result.invalidParamWithMsg("参数错误"));
		}
		vo.createTime = new Date();
		vo.userId = getCurrentUser().id;
		vo.save();
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 判断能否增加
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月6日
	 * @param platform
	 */
	public static void canBind(@Required Platform platform){
		handleWrongInput(false);
		User user = getCurrentUser();
		int count = BuyerAccount.accountCount(platform, user.id);
		
		if(platform==Platform.TAOBAO){
			if(count>=2){
				renderJSON(Result.errorWithMsg("淘宝最多只能绑定两个账号"));
			}
		}else if(platform==Platform.JD){
			if(count>=3){
				renderJSON(Result.errorWithMsg("京东最多只能绑定三个账号"));
			}
		}
		
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 新增买手账号
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月6日
	 * @param account
	 */
	public static void addBuyerAccount(@Required BuyerAccount account) {

		handleWrongInput(false);
		
		if(account.id==0){
		}
		validation.required(account.nick);	
		validation.required(account.mobile);
		validation.required(account.consignee);
		validation.required(account.address);
		validation.required(account.picUrl);
		validation.required(account.platform);
		if("TAOBAO".equals(account.platform.toString())){
			validation.range(account.age, 1, 4);
			validation.range(account.level, 1, 6);
			validation.required(account.gender);
		}
		
		handleWrongInput(false);
		
		// 将无关信息过滤为null
		account.nick = StringUtils.trimToNull(account.nick);
		account.mobile = StringUtils.trimToNull(account.mobile);
		account.consignee = StringUtils.trimToNull(account.consignee);
		account.state = StringUtils.trimToNull(account.state);
		account.city = StringUtils.trimToNull(account.city);
		// 三级行政区域有可能为空，将非空的修改为空值时不能将其设置为null，否则无法构造SQL条件
		account.region = StringUtils.trimToEmpty(account.region);
		account.address = StringUtils.trimToNull(account.address);

		User buyer = getCurrentUser();
		checkBeforeSaveBuyerAccount(account, buyer);

		// 买号改动需要审核
		account.status = ExamineStatus.WAIT_EXAMINE;
		account.userId = buyer.id;
		account.save();
		renderJSON(Result.optSuccess());

	}
	
	/**
	 * 查询账号信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月6日
	 * @param account
	 * @param buyer
	 */
	private static void checkBeforeSaveBuyerAccount(BuyerAccount account, User buyer) {
		Validate.notNull(account.platform);

		boolean isAddNew = account.id <= 0;
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BuyerAccountMapper mapper = ss.getMapper(BuyerAccountMapper.class);
			// 修改买号时检查记录是否存在、是否属于该用户
			if (!isAddNew) {
				BuyerAccount buyerAccount = mapper.selectById(account.id);
				if (buyerAccount == null || !buyerAccount.belongTo(buyer)) {
					logger.warn("Buyer={}-{} save buyerAccount forbidden:{}", buyer.id, buyer.nick, account.toJson());
					renderJSON(Result.errorWithMsg("非法操作"));
				}
			}

			// 检查信息是否重复
			logger.info("Buyer={}-{} save buyerAccount: Check Duplicate", buyer.id, buyer.nick);

			account.userId = buyer.id;
			BuyerAccount buyerAccount = mapper.selectForCheckDuplicate(account);
			if (buyerAccount != null) {
				logger.warn("Buyer={}-{} save buyerAccount forbidden:{}", buyer.id, buyer.nick, account.toJson());
				renderJSON(Result.errorWithMsg("不能重复绑定"));
			}
			// 检查当前已绑定的买号数量（如果是合作商家，无需检查已绑定的买号数）
			if (User.findById(account.userId).vipStatus != VipStatus.SPECIAL
					&& User.findById(account.userId).vipStatus != VipStatus.AIZHUAN) {
				logger.info("Buyer={}-{} save buyerAccount: Check binded count", buyer.id, buyer.nick);

				int count = mapper
						.count(BuyerAccountSearchVo.newInstance().platform(account.platform).userId(account.userId));
				if(account.platform==Platform.MOGUJIE||account.platform==Platform.MEILISHUO){
					return;
				}
				if (isAddNew && count >= 2&&account.platform==Platform.TAOBAO) {
					logger.warn("Buyer={}-{} save buyerAccount forbidden-More than 3 :{}", buyer.id, buyer.nick,
							account.toJson());
					renderJSON(Result.errorWithMsg("淘宝最多绑定两个账号"));
				}
				if (isAddNew && count >= 3&&account.platform==Platform.JD) {
					logger.warn("Buyer={}-{} save buyerAccount forbidden-More than 3 :{}", buyer.id, buyer.nick,
							account.toJson());
					renderJSON(Result.errorWithMsg("京东最多绑定三个账号"));
				}
			}
		} finally {
			ss.close();
		}
	}

	/**
	 * 查询绑定信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月7日
	 */
	public static void getBindInfo(){
		IdentityInfo identityInfo = IdentityInfo.selectOneByUserId(getCurrentUser().id);
		if(identityInfo!=null){
			identityInfo.value();
		}
		renderJSON(Result.optSuccessWithData(identityInfo));
	}
	
	/**
	 * 修改密码
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月8日
	 * @param user
	 * @param oldPass
	 */
	public static void modifyPwd(@Required User user, String oldPass) {
		handleWrongInput(false);
		User u = getCurrentUser();
		user.id = u.id;
		/*
		 * 修改登录密码时，检查填写的旧密码是否正确
		 */
		if (StringUtils.isNotBlank(oldPass) && !u.validate(oldPass)) {
			renderJSON(Result.errorWithMsg("您输入的旧密码错误，请重新输入"));
		}
		
		user.updatePass(user.id, user.password);
		
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 金币提现
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月9日
	 */
	public static void getIngotFundInfo(){
		Map<String, Object> retData =new HashMap<String, Object>();
		FundAccount fundAccount = FundAccount.findBank(getCurrentUser().id);
		retData.put("acountData", fundAccount);
		retData.put("bankName", fundAccount.type.title);
		
		retData.put("ingot", UserService.getUserInfo(params.get("imei")).getIngot());
		
		renderJSON(Result.optSuccessWithData(retData));
	}
	
	/**
	 * 查询银行账号
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月9日
	 */
	public static void getCapitalFundInfo(){
		
		Map<String, Object> retData =new HashMap<String, Object>();
		FundAccount fundAccount = FundAccount.findBank(getCurrentUser().id);
		
		if(fundAccount==null){
			renderJSON(Result.errorWithMsg("请绑定提现账户"));
		}
		
		retData.put("acountData", fundAccount);
		retData.put("bankName", fundAccount.type.title);
		
		TaskSearchVo vo = new TaskSearchVo();
		vo.pageNo = 1;
		vo.pageSize = Integer.MAX_VALUE;

        long BuyerId = getCurrentUser().id;
        vo.buyerId(BuyerId).pageSize(Integer.MAX_VALUE);
        vo.module(SearchModule.SYS_REFUND_WITHDRAW);
        
        Page<BuyerTaskVo> p = BuyerTask.findListByPage(vo);
        
        StringBuilder sb = new StringBuilder();
        for(BuyerTaskVo b : p.items){
        	if(BooleanUtils.isTrue(b.sysRefund)){
        		sb.append(b.id + ",");
        	}
        }
        
        int index = sb.lastIndexOf(",");
        if(index!=-1){
        	sb.deleteCharAt(sb.lastIndexOf(","));
        }
        retData.put("idsStr", sb.toString());
        
        long paidFee = 0;
        
        for(BuyerTaskVo b : p.items){
        	paidFee += b.paidFee;
        }
        
        retData.put("canWithdrawCash", UserService.statisticsCanWithdrawCash(getCurrentUser()));
        
        retData.put("padPayment", UserService.statisticsPadPayment(getCurrentUser()));
        
		renderJSON(Result.optSuccessWithData(retData));
		
	}
	
	/**
	 * 提现
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月9日
	 * @param tids
	 * @param payPass
	 */
	public synchronized static void applyBuyerDepositWithdraw(@Required String tids,
			@Required String payPass) {
		
		handleWrongInput(false);
		
		String[] ids = tids.split(",");
		
		List<Long> buyerTaskIds = new ArrayList<>();
		
		for(String id : ids){
			try{
				buyerTaskIds.add(Long.parseLong(id));
			}catch(Exception ex){
				logger.error("提现时ID转换错误");
			}
		}
		
		if(buyerTaskIds.size()==0){
			renderJSON(Result.invalidParam());
		}
		
		User buyer = getCurrentUser();
		// 检查支付密码
		if (Strings.isNullOrEmpty(buyer.payPassword)) {
			renderJSON(Result.errorWithMsg("需要先设置支付密码~~"));
		}
		if (!StringUtils.equals(payPass, buyer.payPassword)) {
			renderJSON(Result.errorWithMsg("支付密码不正确"));
		}

		// 检查是否设置银行卡
		FundAccount bank = FundAccount.findBank(buyer.id);
		if (bank == null) {
			renderJSON(Result.errorWithMsg("需要先绑定银行卡~~"));
		}
		
		// 提现金额后续使用任务垫付资金来计算得出
		UserWithdrawRecord.newInstance(0).createDepositApply(bank, buyerTaskIds);
		
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 提现佣金
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月9日
	 * @param amount
	 * @param payPass
	 */
	public synchronized static  void applyWithdraw(@Required int amount,
			@Required String payPass) {
		
		// 最少100元
		User user = getCurrentUser();
		if(user.vipStatus==VipStatus.AIZHUAN){
			validation.min("amount", amount, 50);
		}
		else{
			validation.min("amount", amount, 100);
		}
		handleWrongInput(false);
		// 检查支付密码
		if (Strings.isNullOrEmpty(user.payPassword)) {
			renderJSON(Result.errorWithMsg("需要先设置支付密码~~"));
		}
		if (!StringUtils.equals(payPass, user.payPassword)) {
			renderJSON(Result.errorWithMsg("支付密码不正确"));
		}

		// 检查账户余额是否足够：卖家提现押金，买手提现金币
		long centAmount = amount * 100;
		if (user.type == UserType.SELLER) {
			validation.min(user.pledge, centAmount);
		} else {
			validation.min(user.ingot, centAmount);
		}
		handleWrongInput(false);

		/*
		 * 检查是否设置提现账号 1、卖家必须已绑定银行卡 2、买手必须已绑定银行卡 与 财付通
		 */
		FundAccount bank = FundAccount.findBank(user.id);
		if (user.isSeller() && bank == null) {
			renderJSON(Result.errorWithMsg("必须先绑定【银行卡】账号~~"));
		}

		// 检查本月已申请提现次数：申请次数不计入
		if (user.isBuyer()) {
			WithdrawSearchVo svo = WithdrawSearchVo.newInstance().userId(
					user.id);
			if (UserWithdrawRecord.countThisMonthApply(svo) >= 3) {
				renderJSON(Result.errorWithMsg("每个月最多申请提现3次~~"));
			}
		}

		UserWithdrawRecord.newInstance(centAmount).createApply(user);
		
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 资金明细
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月10日
	 * @param vo
	 */
	public static void listFundRecord(@Required MoneyRecordSearchVo vo) {
		if (vo != null) {
			validation.required("vo.type", vo.type);
			validation.min("vo.pageNo", vo.pageNo, 1);
			validation.max("vo.pageNo", vo.pageNo, 100);
			validation.max(vo.pageSize, 50);
		}
		handleWrongInput(false);

		vo.pageSize = Math.min(vo.pageSize, 20);
		vo.userId = getCurrentUser().id;
		Page p = findPageBySearchVo(vo);
		renderJSON(Result.optSuccessWithData(p));
	}
	
	private static Page findPageBySearchVo(MoneyRecordSearchVo vo) {
		switch (vo.type) {
		case member:
			return MemberChargeRecord.findByPage(vo);
		case pledge:
			return SellerPledgeRecord.findByPage(vo);
		case ingot:
			return UserIngotRecord.findByPage(vo);
		case withdraw:
			return UserWithdrawRecord.findByPage(vo);
		case premium:
			return UserIngotRecord.findByPage(vo);
		case deposit:
			return BuyerDepositRecord.findByPage(vo);
		case flow:
			return UserFlowRecord.findByPage(vo);
		default:
			return Page.EMPTY;
		}
	}
	
	/**
	 * 会员续费
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月10日
	 * @param month
	 */
	public static void memberCharge(@Required Integer month) {

		User user = getCurrentUser();
		user = user.findById(user.id);

		// 检查会员费用
		long payFee = MemberChargeRecord.getRechargeAmount(user.type, month);
		validation.min("payFee", payFee, 100);
		validation.range(month, 1, 24);

		handleWrongInput(false);

		// 使用押金或金币支付
		MemberChargeRecord r = MemberChargeRecord.newInstance(user.id, month)
				.userType(user.type).amount(payFee);
		boolean result = r.create(true, false);
		if (!result) {
			renderJSON(Result.errorWithMsg("续费失败,请检查会员余额是否充足"));
		}
		// 给用户升级会员到VIP1、VIP2、VIP3
		Integer minMonth = BizConstants.UPGRADE_NORMAL_COUNT;
		if (user.vipStatus == VipStatus.VIP1) {
			minMonth = BizConstants.UPGRADE_VIP1_COUNT;
		} else if (user.vipStatus == VipStatus.VIP2) {
			minMonth = BizConstants.UPGRADE_VIP2_COUNT;
		} else if (user.vipStatus == VipStatus.VIP3) {
			minMonth = BizConstants.UPGRADE_VIP3_COUNT;
		}
		if (minMonth < month) {
			VipStatus vipStatus = VipStatus.NORMAL;
			if (BizConstants.UPGRADE_VIP1_COUNT <= month
					&& month < BizConstants.UPGRADE_VIP2_COUNT) {
				vipStatus = VipStatus.VIP1;
			} else if (BizConstants.UPGRADE_VIP2_COUNT <= month
					&& month < BizConstants.UPGRADE_VIP3_COUNT) {
				vipStatus = VipStatus.VIP2;
			} else {
				vipStatus = VipStatus.VIP3;
			}

			user.changeVipStatus(user.id, vipStatus);
		}
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 查询买号
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月10日
	 * @param platform
	 * @param receive
	 */
	public static void listBuyerAccounts(Platform platform) {
		if (platform == Platform.TMALL||platform==null) {
			platform = Platform.TAOBAO;
		}
		BuyerAccountSearchVo vo = BuyerAccountSearchVo.newInstance()
				.platform(platform).userId(getCurrentUser().id);
		List<BuyerAccount> list = BuyerAccount.findList(vo);
		renderJSON(Result.optSuccessWithData(list));
	}
	
	/**
	 * 根据ID账户买号
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月10日
	 * @param id
	 */
	public static void getBuyerAccountById(@Required Long id){
		handleWrongInput(false);
		
		BuyerAccount buyerAccount = BuyerAccount.findById(id);
		
		if(buyerAccount==null){
			renderJSON(Result.resourceNotFoundWithMsg("未找到相关信息"));
		}
		
		boolean belongTo = buyerAccount.belongTo(getCurrentUser());
		if(!belongTo){
			renderJSON(Result.errorWithMsg("无编辑权限"));
		}
		
		if(buyerAccount.status == ExamineStatus.EXAMINED){
			renderJSON(Result.errorWithMsg("当前账户不允许编辑"));
		}
		renderJSON(Result.optSuccessWithData(buyerAccount));
	}
	
	/**
	 * 注册推送信息
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月13日
	 * @param jPush
	 */
	public static void regsiterPush(@Required JPush jPush){
		if(jPush!=null){
			validation.required(jPush.jPushId);
		}
		handleWrongInput(false);
		jPush.userId = getCurrentUser().id;
		jPush.save();
		renderJSON(Result.optSuccess());
	}
	
	/**
	 * 重置密码
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月14日
	 * @param user
	 * @param smsValidCode
	 */
	public static void resetPwd(@Required User user,@Required String smsValidCode){
		if(user!=null){
			validation.required(user.mobile);
			validation.required(user.password);
		}
		
		handleWrongInput(false);
		
		User u = User.findByField("mobile", user.mobile);
		
		if(u==null){
			renderJSON(Result.errorWithMsg("请输入正确的手机号码"));
		}
		
		if (StringUtils.isNotBlank(smsValidCode) && StringUtils.isNotBlank(user.mobile)&&!"888666".equals(smsValidCode)) {
            String key = CacheType.SMS_VALID_CODE.getKey(user.mobile);
            String validCode = CacheUtil.get(key);
            logger.info("User={},input code={} and cachedCode={}", new Object[] { user.nick, smsValidCode, validCode });
            boolean isValidCode = StringUtils.equals(validCode, smsValidCode);
            if(!isValidCode){
            	renderJSON(Result.errorWithMsg("验证码错误"));
            }
        }
		
		user.updatePass(u.id, user.password);
		
		renderJSON(Result.optSuccess());
	}
	
	
	/**
	 * 设置支付密码
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月15日
	 * @param payPass
	 */
	public static void setPayPwd(@Required String payPass){
		handleWrongInput(false);
		User user = User.instance(getCurrentUser().id);
		user.payPassword = payPass;
		user.save(false);
		
		User newUser= getCurrentUser();
		UserInfo userInfo = new UserInfo();
		userInfo.id = newUser.id;
		userInfo.nick = newUser.nick;
		userInfo.dueTime = newUser.dueTime;
		if(!StringUtils.isEmpty(newUser.payPassword)){
			userInfo.payPassword = "******";
		}
		renderJSON(Result.optSuccessWithData(userInfo));
		
	}
	
	/**
	 * 得到绑定状态
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月17日
	 */
	public static void getAllBindInfo(){
		Map<String, Object> bindInfo = new HashMap<String, Object>();
		IdentityInfo identityInfo = IdentityInfo.selectOneByUserId(getCurrentUser().id);
		if(identityInfo!=null){
			identityInfo.value();
		}
		bindInfo.put("identityStatus", 0);
		if(identityInfo!=null&&identityInfo.status==IdentityInfo.CheckStatus.PASS){
			bindInfo.put("identityStatus", 1);
		}
		
		int tbCount = BuyerAccount.accountCount(Platform.TAOBAO, getCurrentUser().id);
		int jdCount = BuyerAccount.accountCount(Platform.JD, getCurrentUser().id);
		int mlsCount = BuyerAccount.accountCount(Platform.MEILISHUO, getCurrentUser().id);
		int mgjCount = BuyerAccount.accountCount(Platform.MOGUJIE, getCurrentUser().id);
		
		bindInfo.put("buyerAccountBindStatus", 0);
		if(tbCount>0&&jdCount>0&&mlsCount>0&&mgjCount>0){
			bindInfo.put("buyerAccountBindStatus", 1);
		}
		
		bindInfo.put("payPassSetStataus", 0);
		User curUser = getCurrentUser();
		if(!StringUtils.isEmpty(curUser.payPassword)){
			bindInfo.put("payPassSetStataus", 1);
		}
		
		renderJSON(Result.optSuccessWithData(bindInfo));
		
		
	}
	
	/**
	 * 查询地区
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年2月14日
	 * @param id
	 */
	public static void region(@Required int id) {
		List<Region> list = Region.findByParentId(id);
		renderJSON(Result.optSuccessWithData(list));
	}
	
}
